from django_filters.rest_framework import FilterSet
from django_filters import FilterSet, CharFilter, DateFilter, BaseInFilter, CharFilter
from .models import *
from django.db.models import Q
from functools import reduce
import operator


class ListCharFilter(BaseInFilter, CharFilter):
    pass


class OfflineDocumentFilterSet(FilterSet):
    name = CharFilter(lookup_expr="contains")
    suffix = ListCharFilter(field_name="name", method="filter_suffix")
    start_time = DateFilter(
        field_name="create_time", lookup_expr="gte", label="开始日期"
    )
    end_time = DateFilter(field_name="create_time", lookup_expr="lt", label="结束日期")

    class Meta:
        model = OfflineDocument
        fields = ["id", "name", "creator", "start_time", "end_time", "suffix"]

    def filter_suffix(self, queryset, name, value):
        # 使用Q对象来构建动态OR查询
        if value:
            queries = [Q(**{f"{name}__iendswith": suffix}) for suffix in value]
            queryset = queryset.filter(reduce(operator.or_, queries))
        return queryset
